<?php

class UserController extends MainController implements ControllerInterface {

    /**
     * Strona glowna
     *
     */
    public function IndexAction($param) {
        $this->AddDescription("");
        $this->AddTitle("");
    }

    public function AddGalleryAction($param) {
        $this->AddDescription(Utils::Translate('add gallery', Registry::Get('_user')));
        $this->AddTitle(Utils::Translate('add gallery', Registry::Get('_user')));

        if (Registry::Get('_userLoggedIn')) {
            $user = Registry::Get('_user');
			
			
			if($this->user->getPremium() == 0)
			{
				return $this->AddRedirectInfo($this->t('buy premium account'), 'info', Router::GenerateUrl('buyPremium'));
			}

            if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                $fileUploaded = true;
                $img = imagecreatefromstring(file_get_contents($_FILES['file']['tmp_name']));
                if ($img !== false) {
                    if (!is_dir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp')) {
                        mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '', 0777, true);
                        mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp', 0777, true);
                    }

                    $fileName = preg_replace('~[^\\pL\d\.]+~u', '-', $_FILES['file']['name']);

                    $temp = $fileName;
                    $counter = 0;
                    while (is_file(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp'))
                        $temp = ++$counter . '_' . $fileName;

                    $fileName = $temp;

                    move_uploaded_file($_FILES['file']['tmp_name'], PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp/' . $fileName);
                    //$product->setMainImage('upload/product/' . $fileName);
                }
            }
            if (!is_dir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp')) {
                mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '', 0777, true);
                mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp', 0777, true);
            }
            if ($handle = opendir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp')) {


                $files = array();

                while (false !== ($file = readdir($handle))) {
                    if ($file != '.' && $file != '..' && is_file(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp/' . $file)) {
                        $files[$file] = '/upload/user/' . $this->user->getId() . '/gallery_tmp/' . $file;
                    }
                }

                if (isset($_GET['remove']) && isset($files[$_GET['remove']])) {
                    unlink(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp/' . $_GET['remove']);
                    unset($files[$_GET['remove']]);
                    $this->AddRedirectInfo($this->T('photo removed successfully'), 'ok', Router::GenerateUrl('current'));
                }

                $this->smarty->assign('files', $files);



                closedir($handle);

                if (isset($_POST['title']) && isset($_POST['description']) && !isset($fileUploaded)) {
                    $data = Request::GetAllPost();

                    $validator = new Validator($data);
                    $validator->IsEmpty('title', $this->t('fulfillment of this field is mandatory'));
                    $validator->IsEmpty('description', $this->t('fulfillment of this field is mandatory'));
                    if (!$validator->IsError()) {


                        $userGallery = new UserGallery();
                        $userGallery->setIdUser($this->user->getId());
                        $userGallery->setDate(date('Y-m-d H:i:s'));
                        $userGallery->setNumPhotos(count($files));
                        $userGallery->setActive('1');
                        //$userGallery->setThumbnail($thumbnail);
                        $userGallery->setTitle($data['title']);
                        $userGallery->setDescription($data['description']);
                        $dalData = UserGalleryDAL::GetDalDataObj();
                        $dalData->setObj($userGallery);
                        $id = UserGalleryDAL::Save($dalData);
                        $this->RunShared('addActivityPoints', array('action' => 'USER_GALLERY', 'idUser' => $this->user->getId()));
                        $userGallery->setId($id);
                        if (!is_dir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery/' . $id)) {
                            @mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '', 0777, true);
                            @mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery', 0777, true);
                            @mkdir(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery/' . $id, 0777, true);
                        }
                        $thumbnail = '';
                        foreach ($files as $name => $file) {
                            rename(PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery_tmp/' . $name, PATH_STATIC_CONTENT . '/upload/user/' . $this->user->getId() . '/gallery/' . $id . '/' . $name);
                            if ($thumbnail == '') {
                                $thumbnail = '/upload/user/' . $this->user->getId() . '/gallery/' . $id . '/' . $name;
                            }
                        }
                        $userGallery->setThumbnail($thumbnail);
                        $dalData->setObj($userGallery);
                        UserGalleryDAL::Save($dalData);
                        $this->AddRedirectInfo($this->T('galery saved successfully'), 'ok', Router::GenerateUrl());
                    } else {
                        $errors = array();
                        foreach ($validator->GetErrorList() as $item) {
                            $errors[$item['field']] = $item['msg'];
                        }

                        $this->smarty->assign('errors', $errors);
                    }
                }
            }
        }
    }

    public function AddVideoAction($param) {
        $this->AddDescription(Utils::Translate('add video', Registry::Get('_user')));
        $this->AddTitle(Utils::Translate('add video', Registry::Get('_user')));

        if (Registry::Get('_userLoggedIn')) {
            $user = Registry::Get('_user');

            if (isset($_POST['title']) && isset($_POST['description'])) {
                $data = Request::GetAllPost();

                $data['video'] = $_POST['video'];

                $validator = new Validator($data);
                $validator->IsEmpty('title', $this->t('fulfillment of this field is mandatory'));
                $validator->IsEmpty('description', $this->t('fulfillment of this field is mandatory'));
                $validator->IsEmpty('video', $this->t('fulfillment of this field is mandatory'));

                if (!$validator->IsError()) {


                    $userGallery = new UserVideo();
                    $userGallery->setIdUser($this->user->getId());
                    $userGallery->setDate(date('Y-m-d H:i:s'));
                    //$userGallery->setNumPhotos(count($files));
                    $userGallery->setActive('1');
                    //$userGallery->setThumbnail($thumbnail);
                    $userGallery->setTitle($data['title']);
                    $userGallery->setDescription($data['description']);
                    $userGallery->setVideo($data['video']);
                    $dalData = UserVideoDAL::GetDalDataObj();
                    $dalData->setObj($userGallery);
                    $id = UserVideoDAL::Save($dalData);
                    $this->RunShared('addActivityPoints', array('action' => 'USER_VIDEO', 'idUser' => $this->user->getId()));
                    $userGallery->setId($id);

                    $dalData->setObj($userGallery);
                    UserVideoDAL::Save($dalData);
                    $this->AddRedirectInfo($this->T('video saved successfully'), 'ok', Router::GenerateUrl());
                } else {
                    $errors = array();
                    foreach ($validator->GetErrorList() as $item) {
                        $errors[$item['field']] = $item['msg'];
                    }

                    $this->smarty->assign('errors', $errors);
                }
            }
        }
    }

    public function GalleryViewAction($param) {
        $this->redirect['url'] = '';
        try {
            if (isset($param['idGallery'])) {
                $idGallery = $param['idGallery'];
                $dalObj = UserGalleryDAL::GetDalDataObj();
                $dalObj->setId($idGallery);
                $obj = UserGalleryDAL::GetById($dalObj);
                if ($obj->getActive() != '1') {
                    throw new UserException('gallery inactive');
                }
                $this->smarty->assign('obj', $obj);



                $dalObj = UserDAL::GetDalDataObj();
                $dalObj->addCondition('user.id_user', $obj->getIdUser());
                $dalObj->addCondition('user.status', '1');
                $dalObj->addJoin('UserExtendedProfile', ' JOIN user_extended_profile on (user.id_user = user_extended_profile.id_user)');



                $user = UserDAL::GetResult($dalObj);

                if (isset($user[0])) {
                    $galeryUser = $user[0];
                } else {
                    throw new UserException('no user');
                }
                $this->AddBreadCrumb($galeryUser->getFirstName() . ' ' . $galeryUser->getLastName(), Router::GenerateUrl('userProfile', array('idUser' => $galeryUser->getId())));
                $this->AddBreadCrumb(Utils::Translate('galleries', Registry::Get('_user')), Router::GenerateUrl('userGalleries', array('idUser' => $galeryUser->getId())));
                $this->AddBreadCrumb($obj->getTitle());
                $dalObj = CommentsDAL::GetDalDataObj();
                $dalObj->addCondition('id_user', $galeryUser->getId());
                $dalObj->addCondition('type', Comments::PRODUCT, '!=');
                $dalObj->setCount('id_comments');

                $galeryUser->setCommentsCount(CommentsDAL::GetResult($dalObj));

                $dalObj = CommentsDAL::GetDalDataObj();
                $dalObj->addCondition('id_user', $galeryUser->getId());
                $dalObj->addCondition('type', Comments::PRODUCT);
                $dalObj->setCount('id_comments');

                $galeryUser->setProductCommentsCount(CommentsDAL::GetResult($dalObj));

                $dalObj = UserConnectionsDAL::GetDalDataObj();
                $dalObj->addCondition('id_user', $galeryUser->getId());
                $dalObj->addCondition('active', '1');
                $dalObj->setCount('id_user_connections');

                $galeryUser->setConnectionsCount(UserConnectionsDAL::GetResult($dalObj));

                $this->smarty->assign('user', $galeryUser);

                $this->AddDescription($obj->getDescription());
                $this->AddTitle($obj->getTitle());
                $files = array();
                if ($handle = opendir(PATH_STATIC_CONTENT . '/upload/user/' . $obj->getIdUser() . '/gallery/' . $obj->getId())) {
                    while (false !== ($file = readdir($handle))) {
                        if ($file != '.' && $file != '..' && is_file(PATH_STATIC_CONTENT . '/upload/user/' . $obj->getIdUser() . '/gallery/' . $obj->getId() . '/' . $file)) {
                            $files[] = '/upload/user/' . $obj->getIdUser() . '/gallery/' . $obj->getId() . '/' . $file;
                        }
                    }
                }
                $selected = 0;
                if (isset($param['page'])) {
                    $selected = $param['page'];
                }
                if (isset($files[$selected]))
                    $this->smarty->assign('image', $files[$selected]);

                $this->smarty->assign('files', $files);
                $this->smarty->assign('selected', $selected);

                $dalObj = UserGalleryDAL::GetDalDataObj();
                $dalObj->addCondition('active', '1');
                $dalObj->addCondition('id_user', $obj->getIdUser());
                $result = UserGalleryDAL::GetResult($dalObj);

                $this->smarty->assign('userGalleries', $result);

                $comments = new Comments();

                if (isset($_POST['comment']) && $_POST['comment'] != '') {
                    $data = Request::GetAllPost();
                    $comments->addComment(array('idProduct' => $obj->getId(), 'title' => '', 'content' => $data['comment'], 'type' => Comments::GALLERY, 'user' => $this->user));
                    $this->RunShared('addActivityPoints', array('action' => 'USER_GALLERY_COMMENT', 'idUser' => $this->user->getId()));
                    $this->AddRedirectInfo(Utils::Translate('comment added', Registry::Get('_user')), 'ok', Router::GenerateUrl('current'));
                }


                $commentList = $comments->GetComments(Comments::GALLERY, $obj->getId());

                $this->smarty->assign('comments', $commentList);
            }
        } catch (Exception $e) {
            $this->AddDescription('');
            $this->AddTitle('');

            $this->AddRedirectInfo(Utils::Translate('gallery cannot be displayed', Registry::Get('_user')), 'error', Router::GenerateUrl());
        }
    }

    public function VideoViewAction($param) {
        $this->redirect['url'] = '';
        try {
            if (isset($param['idGallery'])) {
                $idGallery = $param['idGallery'];
                $dalObj = UserVideoDAL::GetDalDataObj();
                $dalObj->setId($idGallery);
                $obj = UserVideoDAL::GetById($dalObj);
                if ($obj->getActive() != '1') {
                    throw new UserException('video inactive');
                }
                $this->smarty->assign('obj', $obj);

                $dalObj = UserDAL::GetDalDataObj();
                $dalObj->addCondition('user.id_user', $obj->getIdUser());
                $dalObj->addCondition('user.status', '1');
                $dalObj->addJoin('UserExtendedProfile', ' JOIN user_extended_profile on (user.id_user = user_extended_profile.id_user)');


                $user = UserDAL::GetResult($dalObj);
                if (isset($user[0])) {
                    $galeryUser = $user[0];
                } else {
                    throw new UserException('no user');
                }
                $this->AddBreadCrumb($galeryUser->getFirstName() . ' ' . $galeryUser->getLastName(), Router::GenerateUrl('userProfile', array('idUser' => $galeryUser->getId())));
                $this->AddBreadCrumb(Utils::Translate('video', Registry::Get('_user')), Router::GenerateUrl('userVideos', array('idUser' => $galeryUser->getId())));
                $this->AddBreadCrumb($obj->getTitle());
                $dalObj = CommentsDAL::GetDalDataObj();
                $dalObj->addCondition('id_user', $galeryUser->getId());
                $dalObj->addCondition('type', Comments::PRODUCT, '!=');
                $dalObj->setCount('id_comments');

                $galeryUser->setCommentsCount(CommentsDAL::GetResult($dalObj));

                $dalObj = CommentsDAL::GetDalDataObj();
                $dalObj->addCondition('id_user', $galeryUser->getId());
                $dalObj->addCondition('type', Comments::PRODUCT);
                $dalObj->setCount('id_comments');

                $galeryUser->setProductCommentsCount(CommentsDAL::GetResult($dalObj));

                $dalObj = UserConnectionsDAL::GetDalDataObj();
                $dalObj->addCondition('id_user', $galeryUser->getId());
                $dalObj->addCondition('active', '1');
                $dalObj->setCount('id_user_connections');

                $galeryUser->setConnectionsCount(UserConnectionsDAL::GetResult($dalObj));

                $this->smarty->assign('user', $galeryUser);

                $this->AddDescription($obj->getDescription());
                $this->AddTitle($obj->getTitle());






                $dalObj = UserVideoDAL::GetDalDataObj();
                $dalObj->addCondition('active', '1');
                $dalObj->addCondition('id_user', $obj->getIdUser());
                $result = UserVideoDAL::GetResult($dalObj);

                $this->smarty->assign('userGalleries', $result);

                $comments = new Comments();

                if (isset($_POST['comment']) && $_POST['comment'] != '') {
                    $data = Request::GetAllPost();
                    $comments->addComment(array('idProduct' => $obj->getId(), 'title' => '', 'content' => $data['comment'], 'type' => Comments::VIDEO, 'user' => $this->user));
                    $this->RunShared('addActivityPoints', array('action' => 'USER_VIDEO_COMMENT', 'idUser' => $this->user->getId()));
                    $this->AddRedirectInfo(Utils::Translate('comment added', Registry::Get('_user')), 'ok', Router::GenerateUrl('current'));
                }


                $commentList = $comments->GetComments(Comments::VIDEO, $obj->getId());

                $this->smarty->assign('comments', $commentList);
            }
        } catch (Exception $e) {
            $this->AddDescription('');
            $this->AddTitle('');

            $this->AddRedirectInfo(Utils::Translate('gallery cannot be displayed', Registry::Get('_user')), 'error', Router::GenerateUrl());
        }
    }

    public function GalleriesAction($param) {
        $this->redirect['url'] = '';
        try {



            $dalObj = UserDAL::GetDalDataObj();
            $dalObj->addCondition('user.id_user', $param['idUser']);
            $dalObj->addCondition('user.status', '1');
            $dalObj->addJoin('UserExtendedProfile', ' JOIN user_extended_profile on (user.id_user = user_extended_profile.id_user)');


            $user = UserDAL::GetResult($dalObj);
            if (isset($user[0])) {
                $galeryUser = $user[0];
            } else {
                throw new UserException('no user');
            }
            $this->AddBreadCrumb($galeryUser->getFirstName() . ' ' . $galeryUser->getLastName(), Router::GenerateUrl('userProfile', array('idUser' => $galeryUser->getId())));
            $this->AddBreadCrumb(Utils::Translate('galleries', Registry::Get('_user')), Router::GenerateUrl('userGalleries', array('idUser' => $galeryUser->getId())));

            $dalObj = CommentsDAL::GetDalDataObj();
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $dalObj->addCondition('type', Comments::PRODUCT, '!=');
            $dalObj->setCount('id_comments');

            $galeryUser->setCommentsCount(CommentsDAL::GetResult($dalObj));

            $dalObj = CommentsDAL::GetDalDataObj();
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $dalObj->addCondition('type', Comments::PRODUCT);
            $dalObj->setCount('id_comments');

            $galeryUser->setProductCommentsCount(CommentsDAL::GetResult($dalObj));

            $dalObj = UserConnectionsDAL::GetDalDataObj();
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $dalObj->addCondition('active', '1');
            $dalObj->setCount('id_user_connections');

            $galeryUser->setConnectionsCount(UserConnectionsDAL::GetResult($dalObj));

            $this->smarty->assign('user', $galeryUser);

            $this->AddDescription(Utils::Translate('user galleries', Registry::Get('_user')));
            $this->AddTitle(Utils::Translate('user galleries', Registry::Get('_user')));



            $dalObj = UserGalleryDAL::GetDalDataObj();
            $dalObj->addCondition('active', '1');
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $result = UserGalleryDAL::GetResult($dalObj);

            foreach ($result as $row) {
                $files = array();
                $x = 0;
                if ($handle = opendir(PATH_STATIC_CONTENT . '/upload/user/' . $row->getIdUser() . '/gallery/' . $row->getId())) {
                    while (false !== ($file = readdir($handle))) {
                        if ($file != '.' && $file != '..' && is_file(PATH_STATIC_CONTENT . '/upload/user/' . $row->getIdUser() . '/gallery/' . $row->getId() . '/' . $file)) {
                            if ($x < 4) {
                                $files[] = '/upload/user/' . $row->getIdUser() . '/gallery/' . $row->getId() . '/' . $file;
                            }
                            $x++;
                        }
                    }
                }
                $row->files = $files;
            }

            $this->smarty->assign('userGalleries', $result);
        } catch (Exception $e) {
            $this->AddDescription('');
            $this->AddTitle('');

            $this->AddRedirectInfo(Utils::Translate('gallery cannot be displayed', Registry::Get('_user')), 'error', Router::GenerateUrl());
        }
    }

    public function VideosAction($param) {
        $this->redirect['url'] = '';
        try {



            $dalObj = UserDAL::GetDalDataObj();
            $dalObj->addCondition('user.id_user', $param['idUser']);
            $dalObj->addCondition('user.status', '1');
            $dalObj->addJoin('UserExtendedProfile', ' JOIN user_extended_profile on (user.id_user = user_extended_profile.id_user)');


            $user = UserDAL::GetResult($dalObj);
            if (isset($user[0])) {
                $galeryUser = $user[0];
            } else {
                throw new UserException('no user');
            }
            $this->AddBreadCrumb($galeryUser->getFirstName() . ' ' . $galeryUser->getLastName(), Router::GenerateUrl('userProfile', array('idUser' => $galeryUser->getId())));
            $this->AddBreadCrumb(Utils::Translate('videos', Registry::Get('_user')), Router::GenerateUrl('userVideos', array('idUser' => $galeryUser->getId())));
            $dalObj = CommentsDAL::GetDalDataObj();
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $dalObj->addCondition('type', Comments::PRODUCT, '!=');
            $dalObj->setCount('id_comments');

            $galeryUser->setCommentsCount(CommentsDAL::GetResult($dalObj));

            $dalObj = CommentsDAL::GetDalDataObj();
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $dalObj->addCondition('type', Comments::PRODUCT);
            $dalObj->setCount('id_comments');

            $galeryUser->setProductCommentsCount(CommentsDAL::GetResult($dalObj));

            $dalObj = UserConnectionsDAL::GetDalDataObj();
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $dalObj->addCondition('active', '1');
            $dalObj->setCount('id_user_connections');

            $galeryUser->setConnectionsCount(UserConnectionsDAL::GetResult($dalObj));

            $this->smarty->assign('user', $galeryUser);

            $this->AddDescription(Utils::Translate('user videos', Registry::Get('_user')));
            $this->AddTitle(Utils::Translate('user videos', Registry::Get('_user')));



            $dalObj = UserVideoDAL::GetDalDataObj();
            $dalObj->addCondition('active', '1');
            $dalObj->addCondition('id_user', $galeryUser->getId());
            $result = UserVideoDAL::GetResult($dalObj);



            $this->smarty->assign('userGalleries', $result);
        } catch (Exception $e) {
            $this->AddDescription('');
            $this->AddTitle('');

            $this->AddRedirectInfo(Utils::Translate('video cannot be displayed', Registry::Get('_user')), 'error', Router::GenerateUrl());
        }
    }

    public function AjaxRateGalleryAction($param) {
        $this->SetAjaxRender();
        $this->SetNoRender();
        if ($this->userLoggedIn) {
            if (isset($param['idGallery']) && isset($param['like']) && !isset($_COOKIE['gallery' . $param['idGallery']])) {
                try {
                    $idGallery = $param['idGallery'];
                    $dalObj = UserGalleryDAL::GetDalDataObj();
                    $dalObj->setId($idGallery);
                    $obj = UserGalleryDAL::GetById($dalObj);
                    if ($obj->getActive() != '1') {
                        throw new UserException('gallery inactive');
                    }

                    if ($param['like'] == '1') {
                        $obj->setLikes($obj->getLikes() + 1);
                        $r = 'LIKE';
                    } else {
                        $obj->setDislikes($obj->getDislikes() + 1);
                        $r = 'DISLIKE';
                    }

                    $dalObj->setObj($obj);
                    UserGalleryDAL::Save($dalObj);
                    $this->RunShared('addActivityPoints', array('action' => 'USER_GALLERY_RATE', 'idUser' => $this->user->getId()));
                    setcookie("gallery" . $param['idGallery'], true, time() + 60 * 60 * 24);
                    echo $r;
                } catch (Exception $e) {
                    echo 'CANT_RATE';
                }
            } else {
                echo 'CANT_RATE';
            }
        } else {
            echo 'NOT_LOGGED';
        }
    }

    public function AjaxRateVideoAction($param) {
        $this->SetAjaxRender();
        $this->SetNoRender();
        if ($this->userLoggedIn) {
            if (isset($param['idGallery']) && isset($param['like']) && !isset($_COOKIE['video' . $param['idGallery']])) {
                try {
                    $idGallery = $param['idGallery'];
                    $dalObj = UserVideoDAL::GetDalDataObj();
                    $dalObj->setId($idGallery);
                    $obj = UserVideoyDAL::GetById($dalObj);
                    if ($obj->getActive() != '1') {
                        throw new UserException('gallery inactive');
                    }

                    if ($param['like'] == '1') {
                        $obj->setLikes($obj->getLikes() + 1);
                        $r = 'LIKE';
                    } else {
                        $obj->setDislikes($obj->getDislikes() + 1);
                        $r = 'DISLIKE';
                    }

                    $dalObj->setObj($obj);
                    UserVideoDAL::Save($dalObj);
                    $this->RunShared('addActivityPoints', array('action' => 'USER_VIDEO_RATE', 'idUser' => $this->user->getId()));
                    setcookie("video" . $param['idGallery'], true, time() + 60 * 60 * 24);
                    echo $r;
                } catch (Exception $e) {
                    echo 'CANT_RATE';
                }
            } else {
                echo 'CANT_RATE';
            }
        } else {
            echo 'NOT_LOGGED';
        }
    }

    public function MessagesAction($param) {
        $this->AddDescription(Utils::Translate('Messages', Registry::Get('_user')));
        $this->AddTitle(Utils::Translate('Messages', Registry::Get('_user')));

        $this->AddBreadCrumb(Utils::Translate('profile', Registry::Get('_user')), null);


        if (Registry::Get('_userLoggedIn')) {
            $user = Registry::Get('_user');


            //county




            $dalData = UserMessagesDAL::GetDalDataObj();


            $dalData->addCondition('((user_messages.deleted_user', '0');
            $dalData->addCondition('user_messages.id_user', $user->getId());
            //$dalData->addCondition('1', 1, ' = ', ') AND');
            $dalData->addCondition('(user_messages.deleted_recipient', '0', ' = ', ') OR ');
            $dalData->addCondition('user_messages.id_recipient', $user->getId());
            $dalData->addCondition('1', 1, ' = ', ')) AND');
            $dalData->addCondition('user_messages.type', '2', '<');
            if (isset($param['threadId'])) {
                $this->smarty->assign('threadView', true);
                $this->AddBreadCrumb(Utils::Translate('messages', Registry::Get('_user')), Router::GenerateUrl('messages'));

                $dalData2 = UserMessagesDAL::GetDalDataObj();
                $dalData2->setId($param['threadId']);
                $obj = UserMessagesDAL::GetById($dalData2);
                if (isset($obj) && $obj->getIdUser() != $user->getId()) {
                    $obj->setReadedRecipient(1);
                    $obj->setThreadReadedRecipient(1);
                } else {
                    $obj->setReadedUser(1);
                    $obj->setThreadReadedUser(1);
                }
                /* if($obj->getIdUser()==$user->getId())
                  $obj->setThreadReadedUser(0);
                  else
                  $obj->setThreadReadedRecipient(0); */

                if ($obj->getType() == 1) {
                    if (isset($_GET['action']) && $_GET['action'] == 'accept') {
                        $dalCon = UserConnectionsDAL::GetDalDataObj();
                        $userCon = new UserConnections();
                        $userCon->setActive(1);
                        $userCon->setIdUser($obj->getIdUser());
                        $userCon->setIdUserTarget($obj->getIdRecipient());
                        $dalCon->setObj($userCon);
                        UserConnectionsDAL::Save($dalCon);
                        $dalCon = UserConnectionsDAL::GetDalDataObj();
                        $userCon = new UserConnections();
                        $userCon->setActive(1);
                        $userCon->setIdUserTarget($obj->getIdUser());
                        $userCon->setIdUser($obj->getIdRecipient());
                        $dalCon->setObj($userCon);
                        UserConnectionsDAL::Save($dalCon);
                        $_GET = array();

                        $this->AddRedirectInfo(Utils::Translate('user added to Your contacts', Registry::Get('_user')), 'ok', Router::GenerateUrl('messages'));
                    } else {
                        $this->AddRedirectInfo(Utils::Translate('user not added to Your contacts', Registry::Get('_user')), 'ok', Router::GenerateUrl('messages'));
                    }
                }

                $dalData2->setObj($obj);
                UserMessagesDAL::Save($dalData2);
                $dalData2->setId('');
                $dalData2->setObj('');
                $dalData2->setLimit('');

                $dalData->addCondition('(id_thread', $param['threadId'] . '\' OR id_user_messages = ' . $param['threadId'] . ') AND 1=\'1');
                //$dalData->addCondition('id_user_messages', $param['threadId'].')');

                if (isset($_POST['message'])) {
                    $message = new UserMessages();
                    $message->setContent(Request::GetPost('message', false));
                    $message->setIdRecipient(Request::GetPost('recipientId', false));
                    $message->setIdUser($user->getId());
                    $message->setIdThread($param['threadId']);
                    $message->setDate(date("Y-m-d H:i:s"));
                    $message->setReadedUser(1);
                    $message->setThreadReadedUser(1);
                    $this->saveMessage($message);

                    $this->AddRedirectInfo(Utils::Translate('message sent', Registry::Get('_user')), 'ok', Router::GenerateUrl('messagesThread', array('threadId' => $param['threadId'])));
                }
            } else {
                $dalData->addCondition('user_messages.id_thread', '0');
                //$dalData->addJoin('UserMessages', ' LEFT JOIN user_messages as UM ON (UM.id_user_messages = user_messages.id_thread AND UM.readed = 0)');
                $this->AddBreadCrumb(Utils::Translate('messages', Registry::Get('_user')), null);
            }
            //$dalData->addCondition('(user_messages.id_user', $user->getId());
            //$dalData->addCondition('user_messages.id_recipient', $user->getId().')', '=', 'OR');
            $dalData->addJoin('User', " JOIN user ON (user.id_user = user_messages.id_user) ");
            $dalData->setOrderBy('user_messages.date DESC');


            $result = UserMessagesDAL::GetResult($dalData);

            if (isset($param['threadId']) && isset($result[(count($result) - 1)])) {
                $this->AddBreadCrumb($result[(count($result) - 1)]->getTitle(), null);
                if (isset($_POST['message'])) {
                    //die('111');
                    if ($result[(count($result) - 1)]->getIdUser() == $user->getId()) {
                        $result[(count($result) - 1)]->setThreadReadedRecipient('0');
                    } else {
                        $result[(count($result) - 1)]->setThreadReadedUser('0');
                    }

                    $dalData = UserMessagesDAL::GetDalDataObj();
                    $dalData->setObj($result[(count($result) - 1)]);
                    UserMessagesDAL::Save($dalData);
                }
                $this->smarty->assign('enableReply', true);
            }

            if (isset($param['threadId'])) {
                $recipient = '';
                foreach ($result as $row) {
                    if ($row->getReadedRecipient() == '0' && $row->getIdRecipient() == $user->getId()) {
                        $row->setReadedRecipient(1);
                        $row->setThreadReadedRecipient(1);
                        $dalData->setObj($row);
                        UserMessagesDAL::Save($dalData);
                    }
                    if ($row->getIdRecipient() != $user->getId()) {
                        $recipient = $row->getIdRecipient();
                    }
                    if ($row->getIdUser() != $user->getId()) {
                        $recipient = $row->getIdUser();
                    }
                }
                $this->smarty->assign('recipientId', $recipient);
            }

            if (isset($_POST['deleteMessages'])) {
                $x = 0;
                $deleted = false;
                foreach ($result as $row) {
                    if (isset($_POST['msg' . $row->getId()])) {
                        unset($result[$x]);
                        if ($row->getIdUser() == $user->getId())
                            $row->setDeletedUser(1);
                        else
                            $row->setDeletedRecipient(1);
                        $dalDataDelete = UserMessagesDAL::GetDalDataObj();
                        $dalDataDelete->setObj($row);
                        UserMessagesDAL::Update($dalDataDelete);
                        $deleted = true;
                    }
                    $x++;
                }
                if ($deleted == true) {
                    $this->AddRedirectInfo(Utils::Translate('messages deleted', Registry::Get('_user')), 'ok', Router::GenerateUrl('current'));
                }
            }


            $this->smarty->assign('messages', $result);

            $dalData = UserMessagesDAL::GetDalDataObj();



            $dalData->addCondition('deleted_user', '0');
            $dalData->addCondition('type', '1', '>');
            $dalData->addCondition('id_recipient', $user->getId());
            $dalData->addJoin('User', " JOIN user ON (user.id_user = user_messages.id_user) ");


            $result = UserMessagesDAL::GetResult($dalData);

            $this->smarty->assign('noticeCount', count($result));
            $this->smarty->assign('notice', $result);

            $dalCount = UserMessagesDAL::GetDalDataObj();
            $dalCount->setCount('COUNT(id_user_messages)');
            $dalCount->addCondition('deleted_user', '0');
            $dalCount->addCondition('type', '2', '<');
            $dalCount->addCondition('readed_recipient', '0');
            //$dalCount->addCondition('(user_messages.id_user', $user->getId());
            $dalCount->addCondition('id_recipient', $this->user->getId());

            $countMessages = UserMessagesDAL::GetResult($dalCount);
            $this->smarty->assign('messagesCount', $countMessages);
        }
    }

    public function removeConnectAction($param) {
        $this->AddDescription('');
        $this->AddTitle('');
        if (isset($param['idUser']) && $this->userLoggedIn) {
            $dalCon = UserConnectionsDAL::GetDalDataObj();
            $dalCon->addCondition('active', '1');
            $dalCon->addCondition('id_user', $param['idUser']);
            $dalCon->addCondition('id_user_target', $this->user->getId());
            $obj = UserConnectionsDAL::GetResult($dalCon);
            if(isset($obj[0]) && is_object($obj[0])) {
                $dalCon->setObj($obj[0]);
                UserConnectionsDAL::Delete($dalCon);
            }
            $dalCon = UserConnectionsDAL::GetDalDataObj();
            $dalCon->addCondition('active', '1');
            $dalCon->addCondition('id_user_target', $param['idUser']);
            $dalCon->addCondition('id_user', $this->user->getId());
            $obj = UserConnectionsDAL::GetResult($dalCon);
            if(isset($obj[0]) && is_object($obj[0])) {
                $dalCon->setObj($obj[0]);
                UserConnectionsDAL::Delete($dalCon);
            }
            $this->AddRedirectInfo(Utils::Translate('connection removed', Registry::Get('_user')), 'ok', Router::GenerateUrl());
        } else {
            $this->AddRedirectInfo(Utils::Translate('could not remove connection', Registry::Get('_user')), 'error', Router::GenerateUrl());
        }
    }

    private function saveMessage($message) {
        $dalObj = UserMessagesDAL::GetDalDataObj();
        $dalObj->setObj($message);
        UserMessagesDAL::Save($dalObj);
        return true;
    }

    public function AddConnectAction($param) {
        $this->AddDescription(Utils::Translate('add user connection', Registry::Get('_user')));
        $this->AddTitle(Utils::Translate('add user connection', Registry::Get('_user')));
        $this->AddBreadCrumb(Utils::Translate('profile', Registry::Get('_user')), Router::GenerateUrl('profile'));
        $this->AddBreadCrumb(Utils::Translate('messages', Registry::Get('_user')), Router::GenerateUrl('userMessages'));
        $this->AddBreadCrumb(Utils::Translate('connect to friend', Registry::Get('_user')));
        if (Registry::Get('_userLoggedIn')) {
            $user = Registry::Get('_user');

            if (isset($param['idUser'])) {
                try {
                    $dalObj = UserDAL::GetDalDataObj();
                    $dalObj->setId($param['idUser']);

                    $dalObj = UserDAL::GetDalDataObj();
                    //$dalObj->setId($param['idUser']);
                    $dalObj->addCondition('user.id_user', $param['idUser']);
                    $dalObj->addCondition('status', '1');
                    $dalObj->addJoin('UserExtendedProfile', ' JOIN user_extended_profile on (user.id_user = user_extended_profile.id_user)');
                    $usera = UserDAL::GetResult($dalObj);
                    if (isset($usera[0])) {
                        $usera = $usera[0];
                    } else {
                        throw new UserException('no user');
                    }

                    $this->smarty->assign('user', $usera);


                    if (isset($_POST['message'])) {
                        $message = new UserMessages();
                        $message->setTitle(Utils::Translate('please add me to your contacts', Registry::Get('_user')));
                        $message->setContent(Request::GetPost('message'));
                        $message->setIdRecipient($param['idUser']);
                        $message->setIdUser($user->getId());
                        //$message->setIdThread($param['threadId']);
                        $message->setDate(date("Y-m-d H:i:s"));
                        $message->setType(1);
                        $this->saveMessage($message);

                        $this->AddRedirectInfo(Utils::Translate('invitation sent', Registry::Get('_user')), 'ok', Router::GenerateUrl('messages'));
                    }
                } catch (Exception $e) {
                    $this->AddRedirectInfo(Utils::Translate('no user found', Registry::Get('_user')), 'error', Router::GenerateUrl());
                }
            } else {
                $this->AddRedirectInfo(Utils::Translate('no user found', Registry::Get('_user')), 'error', Router::GenerateUrl());
            }
        }
    }

    public function AddMessageAction($param) {
        $this->AddDescription(Utils::Translate('add message', Registry::Get('_user')));
        $this->AddTitle(Utils::Translate('add message', Registry::Get('_user')));
        $this->AddBreadCrumb(Utils::Translate('profile', Registry::Get('_user')), Router::GenerateUrl('profile'));
        $this->AddBreadCrumb(Utils::Translate('messages', Registry::Get('_user')), Router::GenerateUrl('userMessages'));
        $this->AddBreadCrumb(Utils::Translate('new message', Registry::Get('_user')));
        if (Registry::Get('_userLoggedIn')) {
            $user = Registry::Get('_user');

            if (isset($param['idUser'])) {
                try {
                    $dalObj = UserDAL::GetDalDataObj();
                    $dalObj->setId($param['idUser']);

                    $this->smarty->assign('user', UserDAL::GetById($dalObj));


                    if (isset($_POST['message'])) {
                        $message = new UserMessages();
                        $message->setTitle(Request::GetPost('subject', false));
                        $message->setContent(Request::GetPost('message', false));
                        $message->setIdRecipient($param['idUser']);
                        $message->setIdUser($user->getId());
                        $message->setReadedUser(1);
                        $message->setThreadReadedUser(1);
                        $message->setDate(date("Y-m-d H:i:s"));
                        //$message->setType(1);
                        $this->saveMessage($message);

                        $this->AddRedirectInfo(Utils::Translate('message sent', Registry::Get('_user')), 'ok', Router::GenerateUrl('messages'));
                    }
                } catch (Exception $e) {
                    $this->AddRedirectInfo(Utils::Translate('no user found', Registry::Get('_user')), 'error', Router::GenerateUrl());
                }
            } else {
                $this->AddRedirectInfo(Utils::Translate('no user found', Registry::Get('_user')), 'error', Router::GenerateUrl());
            }
        }
    }

    /**
     * Czesc wspolna wszystkich podstron
     *
     */
    public function PreDispatch($param) {
        $this->addScript('autoresize.jquery.min.js', 'file', 'top', 13);
        $this->Run($param);
        //var_dump($param);
        //die();
        if (Registry::Get('_userLoggedIn') || $param['methodToRun'] == 'GalleryView' || $param['methodToRun'] == 'VideoView' || $param['methodToRun'] == 'Galleries' || $param['methodToRun'] == 'Videos' || $param['methodToRun'] == 'AjaxRateVideo' || $param['methodToRun'] == 'AjaxRateGallery') {
            
        } else {
            $this->SetNoRender();
            $this->SetAjaxRender();
            $this->AddRedirectInfo(Utils::Translate('You must be logged in', Registry::Get('_user')), 'error', Router::GenerateUrl());
        }
    }

    public function PostDispatch($param) {

        // nagłówek strony
        $this->RunShared('Header', $param);


        // footer
        $this->RunShared('Footer', $param);
    }

    public function AjaxValidateEditprofileAction($param, $as_action = true) {
        if ($as_action)
            $param['validation_data'] = array();

        $validator = new Validator($param['validation_data']);
        $validator->IsEmpty('first_name', $this->t('Enter your name'));
        $validator->IsEmpty('last_name', $this->t('Enter your family name'));
        $validator->IsEmpty('gender', $this->t('Enter your gender'));
		$validator->IsShorter('password', 4, $this->t('Password should be longer than 4 characters'));
        $validator->IsEmpty('password', $this->t('Enter password'));
        $validator->IsEmpty('password2', $this->t('Reenter your password'));
        $validator->IsNotEqual('password2', 'password', $this->t('Passwords aren\'t same'));
		
		$validator->IsNumber('weight', $this->t('Incorrect value'));
		$validator->IsNumber('height', $this->t('Incorrect value'));

        $validator->IsEmpty('email', $this->t('Enter your email'));
        $validator->IsValidOnline('email', $this->t('Specified email address is already registered'), Router::GenerateUrl('ajaxCheckEmail'));

        $this->smarty->assign('js_values', $validator->getJsValues());
        $this->smarty->assign('id_form', Request::GetGet('id_f'));
        $this->smarty->assign('errorClass', 'errorMsg');
        return $validator->getErrorList();
    }

    public function EditprofileAction($param) {
        try {
            $this->AddDescription($this->t("Edit profile"));
            $this->AddTitle($this->t("Edit profile"));
			$this->AddBreadCrumb($this->t("Edit profile"));

            if (empty($this->user) || !$this->userLoggedIn) {
                $this->SetNoRender();
                $this->SetAjaxRender();
                return $this->AddRedirectInfo($this->t('you are not logged in'), 'error', Router::GenerateUrl());
            }

			$permissions = UserProfilePermissionDAL::GetResult(UserProfilePermissionDAL::GetDalDataObj(array(
				'condition' => array(
					'id_user' => $this->user->getId()
				),
				'limit' => 1
			)));

			if(isset($permissions[0])) {
				$permissions = $permissions[0];
			}else{
				$permissions = new UserProfilePermission();
				$permissions->setIdUser($this->user->getId());
			}

			

            if (Request::IsPost()) {
                $obj = UserExtendedProfileDAL::GetResult(
                                UserExtendedProfileDAL::GetDalDataObj(
                                        array(
                                            'condition' => array(
                                                'id_user' => array($this->user->getId())
                                            )
                                        )
                                )
                );

                if (empty($obj)) {
                    $obj = new UserExtendedProfile();
                    $obj->setIdUser($this->user->getId());
                } else {
                    $obj = $obj[0];
                }

                $data = Request::GetAllPost();
                $info = '';

				if(isset($data['profilePermission'])) {
					$permissions->setPlayerProfile($data['permission']['player_profile']);
					$permissions->setExtendedPlayerProfile($data['permission']['extended_player_profile']);
					$permissions->setEquipment($data['permission']['equipment']);
					$permissions->setUserActivity($data['permission']['user_activity']);
					$permissions->setGalleries($data['permission']['galleries']);
					$permissions->setVideos($data['permission']['videos']);

					UserProfilePermissionDAL::Save($permissions->getDalDataObj());

					$info = $this->t('Profile permissions saved');
				}

                if (isset($data['changeEmail']) || ($data['actiontype'] == 'changeEmail')) {
                    if ($data['email'] != $this->user->getEmail()) {
                        $this->user->setEmail($data['email']);
                    }
                    $info = $this->t('Email was saved');
                }

                if (isset($data['changePassword']) || ($data['actiontype'] == 'changePassword')) {
                    $this->user->setPassword(UserDAL::GeneratePassword($data['password']));
                    $info = $this->t('Password was saved');
                }

                if (isset($data['saveSettings']) || ($data['actiontype'] == 'saveSettings')) {
                    $this->user->setFirstName($data['first_name']);
                    $this->user->setLastName($data['last_name']);
                    $this->user->setGender($data['gender']);
                    if (!empty($data['weight'])) {
                        $this->user->setWeight($data['weight']);
                    } else {
                        $this->user->setWeight(null);
                    }
                    if (!empty($data['height'])) {
                        $this->user->setHeight($data['height']);
                    } else {
                        $this->user->setHeight(null);
                    }
                    if (!empty($data['location'])) {
                        $this->user->setLocation($data['location']);
                    } else {
                        $this->user->setLocation(null);
                    }
                    if (!empty($data['state'])) {
                        $this->user->setState($data['state']);
                    } else {
                        $this->user->setState(null);
                    }
                    if (!empty($data['city'])) {
                        $this->user->setCity($data['city']);
                    } else {
                        $this->user->setCity(null);
                    }
                    if (!empty($data['year']) && !empty($data['month']) && !empty($data['day'])) {
                        $this->user->setBirthDate($data['year'] . '-' . $data['month'] . '-' . $data['day']);
                    } else {
                        $this->user->setBirthDate(null);
                    }

                    $this->user->setValuesMetric($data['values_metric']);

                    $this->user->setPriceCompare($data['price_compare']);

					if(isset($data['looking_for_partner']))
					{
						$this->user->setLookingForPartner($data['looking_for_partner']);
					}

                    $obj->setNtrp($data['ntrp']);

                    $info = $this->t('Profile was updated');
                }

                if (isset($data['extendedProfile']) || ($data['actiontype'] == 'extendedProfile')) {
                    if (isset($data['grip_size'])) {
                        $obj->setGripSize($data['grip_size']);
                    } else {
                        $obj->setGripSize(null);
                    }
                    if (isset($data['shoe_size'])) {
                        $obj->setShoeSize($data['shoe_size']);
                    } else {
                        $obj->setShoeSize(null);
                    }
                    if (isset($data['apparel_size'])) {
                        $obj->setApparelSize($data['apparel_size']);
                    } else {
                        $obj->setApparelSize(null);
                    }

                    if (isset($data['hand'])) {
                        $obj->setHand($data['hand']);
                    } else {
                        $obj->setHand(null);
                    }
                    if (isset($data['forehand'])) {
                        $obj->setForehand($data['forehand']);
                    } else {
                        $obj->setForehand(null);
                    }
                    if (isset($data['backhand'])) {
                        $obj->setBackhand($data['backhand']);
                    } else {
                        $obj->setBackhand(null);
                    }
                    if (isset($data['player_style'])) {
                        $obj->setPlayerStyle($data['player_style']);
                    } else {
                        $obj->setPlayerStyle(null);
                    }
                    if (isset($data['average_1'])) {
                        $obj->setAverage1($data['average_1']);
                    } else {
                        $obj->setAverage1(null);
                    }
                    if (isset($data['average_2'])) {
                        $obj->setAverage2($data['average_2']);
                    } else {
                        $obj->setAverage2(null);
                    }
                    if (isset($data['prefered_court_surface'])) {
                        $obj->setPreferedCourtSurface($data['prefered_court_surface']);
                    } else {
                        $obj->setPreferedCourtSurface(null);
                    }
                    if (isset($data['top_player'])) {
                        $obj->setTopPlayer($data['top_player']);
                    } else {
                        $obj->setTopPlayer(null);
                    }
                    if (isset($data['tournament'])) {
                        $obj->setTournament($data['tournament']);
                    } else {
                        $obj->setTournament(null);
                    }

                    $info = $this->t('Settings were saved');
                }

                UserExtendedProfileDAL::Save($obj->GetDalDataObj());
                UserDAL::Update($this->user->GetDalDataObj());
                SessionProxy::SetValue('logged_user', $this->user);

                $this->AddRedirectInfo($info, "ok", Router::GenerateUrl('editProfile'));
            }

            $this->AddStyle(URL_STATIC_CONTENT . '/css/lightbox/prettyPhoto.css');

			

            $this->AddScript('jquery.prettyPhoto.js');
            $this->AddScript('jquery.MFcropper.js');
            $this->smarty->assign('userObj', $this->user);
            $this->smarty->assign('userDate', explode('-', $this->user->getBirthDate()));
            $obj = UserExtendedProfileDAL::GetResult(
                            UserExtendedProfileDAL::GetDalDataObj(
                                    array(
                                        'condition' => array(
                                            'id_user' => array($this->user->getId())
                                        )
                                    )
                            )
            );

            if (empty($obj)) {
                $obj = new UserExtendedProfile();
            } else {
                $obj = $obj[0];
            }
            $this->smarty->assign('extUserProf', $obj);
			
			switch(Registry::Get('METRIC_SYSTEM_TYPE'))
			{
				case 1:
					$sizes = Config::Get('us_shoe_size');
					$sizes = explode(';', $sizes[0]);
					$this->smarty->assign('shoeSize', $sizes);

					$gripSizes = Config::Get('us_grip_size');
					$gripSizes = explode(';', $gripSizes[0]);
					$this->smarty->assign('gripSize', $gripSizes);

					$apparelSizes = Config::Get('us_apparel_size');
					$apparelSizes = explode(';', $apparelSizes[0]);
					$this->smarty->assign('apparelSize', $apparelSizes);				
					break;

				case 0:
				default:
					$sizes = Config::Get('eu_shoe_size');
					$sizes = explode(';', $sizes[0]);
					$this->smarty->assign('shoeSize', $sizes);	

					$gripSizes = Config::Get('eu_grip_size');
					$gripSizes = explode(';', $gripSizes[0]);
					$this->smarty->assign('gripSize', $gripSizes);	

					$apparelSizes = Config::Get('eu_apparel_size');
					$apparelSizes = explode(';', $apparelSizes[0]);
					$this->smarty->assign('apparelSize', $apparelSizes);					
					break;
			}			

            $this->AddScript('jquery-validate/jquery.validate.js');
            $this->AddScript(Router::GenerateUrl('profileValidation') . '?id_f=editProfile');
			$this->smarty->assign('permissions',$permissions);
        } catch (Exception $e) {
            
        }
    }

	public function ajaxChangeEqAction($param) {
		try {
		    header('Content-type: application/javascript');
            $this->SetAjaxRender();
            $this->SetNoRender();	
			
			$idProduct = $param['idProduct'];
			$productObj = new Product();
//			$product = ProductDAL::GetResult($productObj->GetDalDataObj());
//			$product = $product[0];
			
			$userEq = new UserEquipment();
			$competingProductObj = $userEq->getCompetingProduct($productObj->getId(), $this->user->getId());
			$this->smarty->assign('competingProductObj', $competingProductObj);
			
			echo json_encode($this->smarty->fetch('partial/User/AjaxChangeEq.tpl'));
		} catch (Exception $exc) {
//			echo $exc->getTraceAsString();
		}
	}
	
    public function ajaxAddToEqAction($param) {
        try {
            header('Content-type: application/javascript');
            $this->SetAjaxRender();
            $this->SetNoRender();

            $userEq = new UserEquipment();

            $eq = $userEq->GetUserEq($this->user->getId());

            //sprawdza czy produkt znajduje sie w ekwipunku
            $ineq = false;
            foreach ($eq as $item) {
                if ($item->getIdProduct() == $param['idProduct']) {
                    $ineq = true;
                    break;
                }
            }
            if (!$ineq) {
                $userEq->setIdProduct($param['idProduct']);
                $userEq->setIdUser($this->user->getId());
            }
            UserEquipmentDAL::Save($userEq->GetDalDataObj());
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function ajaxRemFromEqAction($param) {
        try {
            header('Content-type: application/javascript');
            $this->SetAjaxRender();
            $this->SetNoRender();


            $userEq = new UserEquipment();
            $userEq->setIdProduct($param['idProduct']);
            $userEq->setIdUser($this->user->getId());
            $dalObj = UserEquipmentDAL::GetResult($userEq->GetDalDataObj());
            $dalObj = $dalObj[0];

            UserEquipmentDAL::Delete($dalObj->getDalDataObj());
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
	
	public function PremiumAction($param)
	{
		
		$this->AddDescription($this->t('Buy premium account'));
		$this->AddTitle($this->t('Buy premium account'));
		
		try {
			if(!$this->userLoggedIn)
			{
				return $this->AddRedirectInfo($this->t("you are not logged in"), 'info', Router::GenerateUrl('signIn'));
			}
			

		$this->AddBreadCrumb($this->t('Profile'), Router::GenerateUrl('userProfile', array('idUser'=>$this->user->getId())));
		$this->AddBreadCrumb($this->t('Buy premium account'));			
			
			
			if(Request::IsPost())
			{
				$data = Request::GetPost('buy');
				$package = Request::GetPost('package');
				
				
				$packageObj = PackageDAL::GetResult(PackageDAL::GetDalDataObj(array('condition'=>array('id'=>($package), 'active'=>(1)))));
				
				if(isset($packageObj[0]))
				{
					$packageObj = $packageObj[0];
				}
				
				
				if($data == 1 && $packageObj)
				{
					$this->user->setPremium($data);
					$this->user->setPremiumExpiration(date("Y-m-d H:i:s", strtotime("+ " . $packageObj->getDays() . " days")));
					UserDAL::Update($this->user->getDalDataObj());
					return $this->AddRedirectInfo($this->t("Thank you for buying premium account"), 'info', Router::GenerateUrl('userProfile', array('idUser'=>$this->user->getId())));
				}
			}
			
			$packages = PackageDAL::GetResult(PackageDAL::GetDalDataObj(
					array(
						'condition' => array(
							'active' => array(1)
						),
						'sortBy' => 'days'
					)
					));
			
			$this->smarty->assign('packages', $packages);
			
			
		} catch (Exception $e) {
            echo $e->getMessage();
        }
	
		
	}

}

?>
